﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace Aandelendelen.Payment
{
	public class IdealBanks : Ideal
	{
		BankCollection banks = new BankCollection();

		public IdealBanks(string partnerId)
			: this(partnerId, false)
		{
		}

		public IdealBanks(string partnerId, bool testMode)
			: base(partnerId, testMode)
		{
			this.ProcessRequest(this.banksUrl);
		}

		protected override void ProcessTargetPayResponse(string response)
		{
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(response);

			XmlNodeList bankList = doc.SelectNodes("/issuers/issuer");
			if (bankList.Count == 0)
				this.ThrowXmlException(doc);

			foreach (XmlNode bankNode in bankList)
			{
				string id = null;
				string name = null;

				try
				{
					id = bankNode.Attributes["id"].Value;
					name = bankNode.InnerText;
				}
				catch
				{
				}

				if (string.IsNullOrEmpty(id) == false &&
					string.IsNullOrEmpty(name) == false)
				{
					Bank bank = new Bank(id, name);

					banks.Add(bank);
				}
			}
		}

		protected override void ProcessResponse(XmlDocument doc)
		{
			XmlNodeList bankList = doc.SelectNodes("/response/bank");
			if (bankList.Count == 0)
				this.ThrowXmlException(doc);

			foreach (XmlNode bankNode in doc.SelectNodes("/response/bank"))
			{
				string id = null;
				string name = null;

				foreach (XmlNode bankDetailNode in bankNode.ChildNodes)
				{
					switch (bankDetailNode.Name)
					{
						case "bank_id": id = bankDetailNode.InnerText;
							break;
						case "bank_name": name = bankDetailNode.InnerText;
							break;
					}
				}

				if (string.IsNullOrEmpty(id) == false &&
					string.IsNullOrEmpty(name) == false)
				{
					Bank bank = new Bank(id, name);

					banks.Add(bank);
				}
			}
		}

		public BankCollection Banks
		{
			get { return this.banks; }
		}
	}
}